<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易联机聊天</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                scrollbar-width: none;
                -ms-overflow-style: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .message-animation {
                animation: fadeIn 0.3s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
    <!-- 头部 -->
    <header class="bg-primary text-white shadow-md">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <h1 class="text-xl md:text-2xl font-bold flex items-center">
                <i class="fa fa-comments-o mr-2"></i>简易联机聊天
            </h1>
            <div id="user-info" class="hidden items-center space-x-2">
                <span class="hidden md:inline">当前用户:</span>
                <span id="username-display" class="font-medium"></span>
                <button id="logout-btn" class="text-sm bg-white/20 hover:bg-white/30 px-2 py-1 rounded transition">
                    <i class="fa fa-sign-out mr-1"></i>切换
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-6 flex flex-col md:flex-row gap-6">
        <!-- 聊天区域 -->
        <div class="w-full md:w-2/3 flex flex-col h-[70vh] bg-white rounded-lg shadow-md overflow-hidden">
            <!-- 聊天消息区域 -->
            <div id="chat-messages" class="flex-grow p-4 overflow-y-auto scrollbar-hide space-y-4">
                <div class="text-center text-gray-500 text-sm py-2">
                    欢迎使用简易联机聊天
                </div>
                <div class="text-center text-gray-500 text-sm" id="connection-status">
                    <i class="fa fa-circle-o-notch fa-spin mr-1"></i>连接中...
                </div>
            </div>
            
            <!-- 输入区域 -->
            <div class="border-t p-4 bg-gray-50">
                <div class="flex gap-2">
                    <input 
                        type="text" 
                        id="message-input" 
                        placeholder="输入消息..." 
                        class="flex-grow px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition"
                        disabled
                    >
                    <button 
                        id="send-btn" 
                        class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition disabled:bg-gray-400 disabled:cursor-not-allowed"
                        disabled
                    >
                        <i class="fa fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 侧边栏 - 在线用户 -->
        <div class="w-full md:w-1/3 bg-white rounded-lg shadow-md p-4">
            <h2 class="text-lg font-semibold mb-3 flex items-center">
                <i class="fa fa-users mr-2 text-primary"></i>在线用户
            </h2>
            <div id="user-list" class="space-y-2 max-h-[70vh] overflow-y-auto scrollbar-hide">
                <div class="text-gray-500 text-sm italic">等待用户加入...</div>
            </div>
        </div>
    </main>

    <!-- 昵称设置模态框 -->
    <div id="nickname-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-md">
            <h3 class="text-xl font-bold mb-4 text-center">请设置你的昵称</h3>
            <div class="space-y-4">
                <input 
                    type="text" 
                    id="nickname-input" 
                    placeholder="输入你的昵称" 
                    class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition"
                    maxlength="15"
                >
                <button 
                    id="enter-btn" 
                    class="w-full bg-primary hover:bg-primary/90 text-white py-2 rounded-lg transition font-medium"
                    disabled
                >
                    进入聊天
                </button>
                <p class="text-xs text-gray-500 text-center">
                    提示: 昵称长度不超过15个字符
                </p>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let socket;
        let username = '';
        const wsServer = 'wss://ws.ifelse.io/'; // 使用公共WebSocket服务器
        
        // DOM元素
        const nicknameModal = document.getElementById('nickname-modal');
        const nicknameInput = document.getElementById('nickname-input');
        const enterBtn = document.getElementById('enter-btn');
        const chatMessages = document.getElementById('chat-messages');
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const userList = document.getElementById('user-list');
        const connectionStatus = document.getElementById('connection-status');
        const userInfo = document.getElementById('user-info');
        const usernameDisplay = document.getElementById('username-display');
        const logoutBtn = document.getElementById('logout-btn');
        
        // 初始化事件监听
        function initEventListeners() {
            // 昵称输入验证
            nicknameInput.addEventListener('input', () => {
                enterBtn.disabled = nicknameInput.value.trim() === '';
            });
            
            // 按Enter键进入聊天
            nicknameInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && nicknameInput.value.trim() !== '') {
                    enterChat();
                }
            });
            
            // 点击进入聊天
            enterBtn.addEventListener('click', enterChat);
            
            // 消息输入验证
            messageInput.addEventListener('input', () => {
                sendBtn.disabled = messageInput.value.trim() === '';
            });
            
            // 按Enter键发送消息
            messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && messageInput.value.trim() !== '') {
                    sendMessage();
                }
            });
            
            // 点击发送消息
            sendBtn.addEventListener('click', sendMessage);
            
            // 退出登录
            logoutBtn.addEventListener('click', logout);
        }
        
        // 进入聊天
        function enterChat() {
            username = nicknameInput.value.trim();
            usernameDisplay.textContent = username;
            nicknameModal.classList.add('hidden');
            userInfo.classList.remove('hidden');
            userInfo.classList.add('flex');
            
            // 连接WebSocket
            connectWebSocket();
            
            // 激活输入框
            messageInput.disabled = false;
            messageInput.focus();
        }
        
        // 连接WebSocket服务器
        function connectWebSocket() {
            // 关闭可能存在的连接
            if (socket) {
                socket.close();
            }
            
            // 创建新连接
            socket = new WebSocket(wsServer);
            
            // 连接打开时
            socket.onopen = () => {
                console.log('WebSocket连接已打开');
                updateStatus('已连接', 'text-green-500');
                
                // 发送加入消息
                socket.send(JSON.stringify({
                    type: 'join',
                    username: username
                }));
            };
            
            // 接收消息时
            socket.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    handleMessage(data);
                } catch (error) {
                    console.error('解析消息失败:', error);
                }
            };
            
            // 连接关闭时
            socket.onclose = () => {
                console.log('WebSocket连接已关闭');
                updateStatus('连接已断开，正在重连...', 'text-red-500');
                
                // 尝试重连
                setTimeout(connectWebSocket, 3000);
            };
            
            // 发生错误时
            socket.onerror = (error) => {
                console.error('WebSocket错误:', error);
                updateStatus('连接错误', 'text-red-500');
            };
        }
        
        // 处理接收到的消息
        function handleMessage(data) {
            switch (data.type) {
                case 'join':
                    addSystemMessage(`${data.username} 加入了聊天`);
                    updateUserList(data.users);
                    break;
                case 'leave':
                    addSystemMessage(`${data.username} 离开了聊天`);
                    updateUserList(data.users);
                    break;
                case 'message':
                    addMessage(data.username, data.message, new Date(data.timestamp));
                    break;
                case 'users':
                    updateUserList(data.users);
                    break;
                default:
                    console.log('未知消息类型:', data);
            }
        }
        
        // 添加系统消息
        function addSystemMessage(text) {
            const messageElement = document.createElement('div');
            messageElement.className = 'text-center text-gray-500 text-sm py-1 message-animation';
            messageElement.textContent = text;
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        }
        
        // 添加用户消息
        function addMessage(sender, text, time) {
            const isCurrentUser = sender === username;
            const timeString = time.toLocaleTimeString();
            
            const messageElement = document.createElement('div');
            messageElement.className = `flex ${isCurrentUser ? 'justify-end' : 'justify-start'} message-animation`;
            
            messageElement.innerHTML = `
                <div class="${isCurrentUser ? 'items-end' : 'items-start'} flex max-w-[80%]">
                    <div class="${isCurrentUser ? 'order-2 ml-2' : 'order-1 mr-2'}">
                        <div class="${isCurrentUser ? 'bg-primary text-white' : 'bg-gray-200 text-gray-800'} px-4 py-2 rounded-lg rounded-tl-none">
                            <p>${text}</p>
                        </div>
                        <div class="text-xs text-gray-400 mt-1 ${isCurrentUser ? 'text-right' : ''}">
                            ${isCurrentUser ? timeString : `${sender} · ${timeString}`}
                        </div>
                    </div>
                    ${!isCurrentUser ? `<div class="order-0 h-8 w-8 rounded-full bg-gray-300 flex items-center justify-center text-white font-bold">
                        ${sender.charAt(0).toUpperCase()}
                    </div>` : ''}
                </div>
            `;
            
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        }
        
        // 更新用户列表
        function updateUserList(users) {
            userList.innerHTML = '';
            
            if (users.length === 0) {
                userList.innerHTML = '<div class="text-gray-500 text-sm italic">暂无在线用户</div>';
                return;
            }
            
            users.forEach(user => {
                const userElement = document.createElement('div');
                userElement.className = `flex items-center p-2 rounded ${user === username ? 'bg-primary/10' : 'hover:bg-gray-100'}`;
                userElement.innerHTML = `
                    <div class="h-7 w-7 rounded-full bg-gray-300 flex items-center justify-center text-white font-bold mr-2">
                        ${user.charAt(0).toUpperCase()}
                    </div>
                    <span class="${user === username ? 'font-medium text-primary' : ''}">
                        ${user} ${user === username ? '<span class="text-xs bg-primary text-white px-1 rounded ml-1">你</span>' : ''}
                    </span>
                `;
                userList.appendChild(userElement);
            });
        }
        
        // 发送消息
        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || !socket || socket.readyState !== WebSocket.OPEN) {
                return;
            }
            
            // 发送消息
            socket.send(JSON.stringify({
                type: 'message',
                username: username,
                message: message,
                timestamp: new Date().toISOString()
            }));
            
            // 清空输入框
            messageInput.value = '';
            sendBtn.disabled = true;
        }
        
        // 更新连接状态
        function updateStatus(text, colorClass) {
            connectionStatus.innerHTML = text;
            connectionStatus.className = `text-center text-sm ${colorClass}`;
        }
        
        // 滚动到底部
        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 退出登录
        function logout() {
            if (socket) {
                // 发送离开消息
                socket.send(JSON.stringify({
                    type: 'leave',
                    username: username
                }));
                socket.close();
            }
            
            // 重置状态
            username = '';
            nicknameInput.value = '';
            messageInput.disabled = true;
            sendBtn.disabled = true;
            userInfo.classList.add('hidden');
            userInfo.classList.remove('flex');
            nicknameModal.classList.remove('hidden');
            nicknameInput.focus();
            
            // 清空聊天记录和用户列表
            chatMessages.innerHTML = `
                <div class="text-center text-gray-500 text-sm py-2">
                    欢迎使用简易联机聊天
                </div>
                <div class="text-center text-gray-500 text-sm" id="connection-status">
                    <i class="fa fa-circle-o-notch fa-spin mr-1"></i>连接中...
                </div>
            `;
            userList.innerHTML = '<div class="text-gray-500 text-sm italic">等待用户加入...</div>';
        }
        
        // 初始化应用
        function initApp() {
            initEventListeners();
            nicknameInput.focus();
        }
        
        // 启动应用
        window.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>
